<template>
  <div class="nav-header">
    <div class="header-left">
      <h2>大棚监控系统</h2>
    </div>
    <div class="header-right">
      <el-dropdown @command="handleCommand">
        <span class="user-dropdown">
          <el-icon><User /></el-icon>
          <span>管理员</span>
          <el-icon class="el-icon--right"><CaretBottom /></el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, CaretBottom } from '@element-plus/icons-vue'
import { logout } from '@/api/auth'

const router = useRouter()

const handleCommand = async (command) => {
  if (command === 'logout') {
    try {
      await logout()
      localStorage.removeItem('token')
      router.push('/login')
      ElMessage.success('退出成功')
    } catch (error) {
      ElMessage.error('退出失败')
    }
  }
}
</script>

<style scoped>
.nav-header {
  height: 60px;
  padding: 0 20px;
  background-color: #fff;
  border-bottom: 1px solid #dcdfe6;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left h2 {
  margin: 0;
  color: #409EFF;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #606266;
}

.user-dropdown .el-icon {
  margin: 0 5px;
}

.user-dropdown:hover {
  color: #409EFF;
}
</style>